#pragma once

#include "locallock.hpp"

int count5 = 100;

struct TreadDataCpp5
{
    std::string _name;
    std::mutex *_mymutex;
    TreadDataCpp5(std::string name, std::mutex *_mymutex)
        : _name(name), _mymutex(_mymutex)
    {
    }
    void Lock()
    {
        // std::cout << "lock" << std::endl;
        _mymutex->lock();
    }
    void Unlock()
    {
        // std::cout << "unlock" << std::endl;
        _mymutex->unlock();
    }
};

void *thread5(void *argv)
{
    TreadDataCpp5 *mylock = static_cast<TreadDataCpp5 *>(argv);
    while (1)
    {
        mylock->Lock();
        if (count5 > 0)
        {
            usleep(1000);
            std::cout << "child thread tid: " << mylock->_name << " my count = " << count5 << std::endl;
            count5--;
            mylock->Unlock();
        }
        else
        {
            mylock->Unlock();
            return nullptr;
        }
    }
    return nullptr;
}

// cpp加锁
void cpp_mutex_struct()
{
    std::string myname[5] = {"string1_name", "string2_name", "string3_name", "string4_name", "string5_name"};
    std::mutex mymutex;

    TreadDataCpp5 *td1 = new TreadDataCpp5(myname[0], &mymutex);
    pthread_t pth1_id;
    int pth1_ret = pthread_create(&pth1_id, NULL, thread5, td1);
    TreadDataCpp5 *td2 = new TreadDataCpp5(myname[1], &mymutex);
    pthread_t pth2_id;
    int pth2_ret = pthread_create(&pth2_id, NULL, thread5, td2);
    TreadDataCpp5 *td3 = new TreadDataCpp5(myname[2], &mymutex);
    pthread_t pth3_id;
    int pth3_ret = pthread_create(&pth3_id, NULL, thread5, td3);
    TreadDataCpp5 *td4 = new TreadDataCpp5(myname[3], &mymutex);
    pthread_t pth4_id;
    int pth4_ret = pthread_create(&pth4_id, NULL, thread5, td4);
    TreadDataCpp5 *td5 = new TreadDataCpp5(myname[4], &mymutex);
    pthread_t pth5_id;
    int pth5_ret = pthread_create(&pth5_id, NULL, thread5, td5);

    pthread_detach(pth1_id);
    pthread_detach(pth2_id);
    pthread_detach(pth3_id);
    pthread_detach(pth4_id);
    pthread_detach(pth5_id);

    while (count5 > 0)
    {
        usleep(1000);
    }
    sleep(2);
    delete td1;
    delete td2;
    delete td3;
    delete td4;
    delete td5;
}
